package com.zjbbkj.baibai.netty.message.receive;

import com.alibaba.fastjson.TypeReference;
import com.zjbbkj.baibai.common.utils.wanli.MyUtils;
import com.zjbbkj.baibai.common.utils.wanli.RedisCacheUtil;
import com.zjbbkj.baibai.domain.device.Device;
import com.zjbbkj.baibai.domain.orders.Orders;
import com.zjbbkj.baibai.netty.constants.enums.ResultEnum;
import com.zjbbkj.baibai.netty.feign.DeviceFeignService;
import com.zjbbkj.baibai.netty.feign.OrderFeignService;
import com.zjbbkj.baibai.netty.maps.ContainerMaps;
import com.zjbbkj.baibai.netty.message.factory.Operation;
import com.zjbbkj.baibai.netty.pojo.ProtocolMessage;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.util.Map;
import static com.zjbbkj.baibai.netty.message.factory.OperatorFactory.write;
import static com.zjbbkj.baibai.netty.message.sendpackage.STB.STB_DEVICE;

/**
 * @author WanLi
 * @date 2021年08月24日 17:34
 */

@Slf4j
public class ReceiveRS implements Operation {

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private DeviceFeignService deviceFeignService;

    @Resource
    private OrderFeignService orderFeignService;

    @Override
    public void parsingMsg(String message, Channel channel) {
        String type = message.substring(3, 6);  //指令類型
        try {
            if (type.equals("STA")) {
                STA_HANDLER(message, channel);
            } else if (type.equals("STB")) {
                STB_HANDLER(message, channel);
            } else if (type.equals("STC")) {
                STC_HANDLER(message, channel);
            } else if (type.equals("RUN")) {
                RUN_HANDLER(message, channel);
            } else if (type.equals("STD")) {
                STD_HANDLER(message, channel);
            } else if (type.equals("RUE")) {
                RUN_HANDLER(message, channel);
            } else if (type.equals("CHF")) {
                CHF_HANDLER(message, channel);
            } else if (type.equals("DCA")) {
                DCA_HANDLER(message);
            } else if (type.equals("DCB")) {
                DCB_HANDLER(message);
            } else if (type.equals("DCC")) {
                DCC_HANDLER(message);
            } else if (type.equals("ORD")) {
                ORD_HANDLER(message);
            } else if (type.equals("ORE")) {
                ORE_HANDLER(message);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    /**
     *  设备运行中完整订单信息查询
     * @Description //_RSSTA147852075[1,2,3,4,5]:123456:bless1#/#[6]:123456:bless2#/#[7,8,9,10,11]:123456:bless3\r\n
     * @param message
     * @param channel
     */
    public void STA_HANDLER(String message, Channel channel) {
        try {
            //查询当前设备IMEIID
            String IMEIID = ContainerMaps.getChannelsX().get(channel);
            //解析后存入緩存
            ProtocolMessage p = (ProtocolMessage)redisCacheUtil.hmget(IMEIID);
            String result = message.substring(15, message.length() - 2);
            //TODO 订单号:端口号:端口倒计时:祈福语句
            if(result.contains("#/#")){
                String[] staString = result.split("#/#");
                for (String s: staString) {
                    String[] strings = s.split(":");

                }
            }
//            if (result.contains("#/#")) {
//                //[1,2,3,4,5]:1:123456:bless1#/#[6]:1:123456:bless2#/#[7,8,9,10,11]:1:123456:bless3
//                String[] strings = result.split("#/#");
//                for (String string : strings) {
//                    String[] split = string.split(":");   //[1,2,3,4,5]:1:123456:bless1
//                    String[] port = split[0].replaceAll("[\\[\\]]", "").split(",");//端口号
//                    for (String p : port) {
//                        String[] value = new String[]{port[1], port[2] + port[3]};
//                        map.put(p, value);
//                    }
//                }
//            } else {
//                String[] strings = result.split(":");
//                String[] port = strings[0].split(",");
//                String[] value = new String[]{strings[1], strings[2] + strings[3]};
//                for (String p : port) {
//                    map.put(p, value);
//                }
//            }
//            redisCacheUtil.set(IMEIID + "_STA", JSONUtils.MapToJsonObject(map));
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    /**
     * 更新端口状态
     *
     * @Description //_RSSTB147852045[1,2,3,4,5]:0#/#[6,7,8,9]:1#/#[10,11,12,13]:2\r\n
     * @param message
     * @param channel
     */
    public void STB_HANDLER(String message, Channel channel) {
        try {
            Device device = deviceFeignService.getDevice(ContainerMaps.getChannelsX().get(channel)).getData("device",new TypeReference<Device>(){});
            ProtocolMessage p = (ProtocolMessage)redisCacheUtil.hmget(device.getDeviceImei());
            Map<Object, Object> deviceStb = p.getDeviceStb();
            String[] str = message.substring(15).split("#/#");
            for (String s:str) {
                String[] ports = s.split(":")[0].replaceAll("[\\[\\]]", "").split(",");
                for (String port:ports) {
                    deviceStb.put(port,s.split(":")[1]);
                }
            }
            p.setDeviceStb(deviceStb);
            redisCacheUtil.set(device.getDeviceImei(),p);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }


    public static void STC_HANDLER(String message, Channel channel) {
//        try {
//            //_RSSTC325639013975690:602706
//            RedisService redisService = SpringUtils.getBean(RedisService.class);
//            String IMEIID = GatewayService.getChannelsX().get(channel);
//            String[] str = message.substring(15).split(":");
//            String json = "";
//            for (String orderId : str) {
//                json = json + orderId + ",";
//            }
//            if (!json.contains("NULL")) {
//                redisService.setEncryption(IMEIID + "_STC", json);
//            }
//        } catch (Exception e) {
//            log.info(e.getMessage());
//        }
    }

    public static void STD_HANDLER(String message, Channel channel) {
        try {
            /*
            _RSSTA147852030777777:[2]:1200:621172314E2D56FD0021\r\n
            _RSSTA147852036777777:[1,2,3,4]:1200:621172314E2D56FD0021\r\n*/
            String[] split = message.split(":");
            if (MyUtils.isNull(split[2])) {
                log.info("无端口运行");
            } else {
                String orderNum = split[0].substring(15);
                String port = split[1];
                String time = split[2];
                String PRAY = MyUtils.hexStr2Str(split[3]);
                log.info("订单号:" + orderNum + "    端口号: " + port + "   时间 " + time + "祈福语 " + PRAY);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }


    /**
     * 设备充电回复
     * @param message 收到的消息
     * @param channel 通道
     */
    public void RUN_HANDLER(String message, Channel channel) {
        try {
            //_RSRUN2706430101:220536:1
            write(STB_DEVICE("ALL"), channel);  //更新设备状态
            //sleep(2000);
            String IMEIID = ContainerMaps.getChannelsX().get(channel);
            String json = message.substring(15);
            String[] str = json.split(":");
            Orders order = orderFeignService.getOrderByOrderNum(IMEIID, str[1]).getData("order",new TypeReference<Orders>(){});
            if (MyUtils.isNull(order)) {
//                //走APP
//                TripartiteService tripartiteService = SpringUtils.getBean(TripartiteService.class);
//                Tripartite tripartite = tripartiteService.getTripartiteByNum(split[1], IMEIID);
//                if (!MyUtils.isNull(tripartite)) {
//                    //将num更新
//                    Map<Object, Object> map = redisService.getMap(IMEIID + "_STB");
//                    LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>();
//                    for (String port : tripartite.getBaibaiTripartitePort().split(",")) {
//                        linkedHashMap.put("status", split[2]);
//                        linkedHashMap.put("orderNum", split[1]);
//                        String jsonStr = JSONUtils.JsonObjectToJsonStr(JSONUtils.MapToJsonObject(linkedHashMap));
//                        map.put(port, jsonStr);
//                    }
//                    redisService.setMap(IMEIID + "_STB", map);
//                }
                return;
            }
            ResultEnum result = null;
            if(str[0].equals("1")){
                if(str[2].equals("1")){
                    result = ResultEnum.ADDORDERSTATUSA1;
                }else if(str[2].equals("0")){
                    result = ResultEnum.ADDORDERSTATUSA0;
                }else if(str[2].equals("2")){
                    result = ResultEnum.ADDORDERSTATUSA2;
                }else if(str[2].equals("3")){
                    result = ResultEnum.ADDORDERSTATUSA3;
                }else if(str[2].equals("4")){
                    result = ResultEnum.ADDORDERSTATUSA4;
                }else if(str[2].equals("5")){
                    result = ResultEnum.ADDORDERSTATUSA5;
                }else if(str[2].equals("6")){
                    result = ResultEnum.ADDORDERSTATUSA6;
                }else if(str[2].equals("7")){
                    result = ResultEnum.ADDORDERSTATUSA7;
                }
            }else if(str.equals("2")){
                if (str[2].equals("1")) {
                    result = ResultEnum.MODIFYORDERSTATUSM1;
                }else if(str[2].equals("0")){
                    result = ResultEnum.MODIFYORDERSTATUSM0;
                }else if(str[2].equals("2")){
                    result = ResultEnum.MODIFYORDERSTATUSM2;
                }else if(str[2].equals("3")){
                    result = ResultEnum.MODIFYORDERSTATUSM3;
                }else if(str[2].equals("4")){
                    result = ResultEnum.MODIFYORDERSTATUSM4;
                }else if(str[2].equals("5")){
                    result = ResultEnum.MODIFYORDERSTATUSM5;
                }else if(str[2].equals("6")){
                    result = ResultEnum.MODIFYORDERSTATUSM6;
                }else if(str[2].equals("7")){
                    result = ResultEnum.MODIFYORDERSTATUSM7;
                }
            }else if(str.equals("3")){
                if (str[2].equals("1")) {
                    result = ResultEnum.DELETEORDERSTATUSD1;
                }else if(str[2].equals("0")){
                    result = ResultEnum.DELETEORDERSTATUSD1;
                }else if(str[2].equals("2")){
                    result = ResultEnum.DELETEORDERSTATUSD2;
                }
            }else{
                result = ResultEnum.ERRORORDERSTATUSE0;
            }

            //更新订单状态
            order.setOrderCode(result.getCode().toString());
            order.setOrderExplain(result.getMsg());
            orderFeignService.updateOrder(order);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }


    public static void CHF_HANDLER(String message, Channel channel) {
        log.info(message);
    }

    public static void DCA_HANDLER(String message) {
        //_RSDCA147852004你好\r\n
        String s = message.substring(15);
    }

    public static void DCB_HANDLER(String message) {
        //_RSDCA147852004你好\r\n
        String s = MyUtils.hexStr2Str(message.substring(15));
        log.info(s);
    }

    public static void DCC_HANDLER(String message) {
        String s = MyUtils.hexStr2Str(message.substring(15));
        log.info(s);
    }

    public static void ORD_HANDLER(String message) throws Exception {
        try {
            log.info(message);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    public static void ORE_HANDLER(String message) {
        try {
            log.info(message);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
}
